<?php
/*
 * Login process
 * $Id: login.php 187 2012-03-11 08:40:12Z leikou@163.com $
 */

class Login extends OA_Controller
{
    const CATAGORY = OA_CONST_CATAGORY::COMMON;


    /**
     * @name OA 登录首页
     * @desc OA 登录首页，系统入口
     */
	public function index()
	{
		$vars = array(
			'token_name' => $this->security->get_csrf_token_name(),
			'token_hash' => $this->security->get_csrf_hash(),
			'captcha_image' => $this->session->get_verify_image()
		);
		$this->load->vars($vars);
		
		// prevent captcha image no change
		header('Cache-Control:no-cache');
		header('Expires:Thu, 01 Jan 1970 00:00:01 GMT');
		
		$this->load->view('login');
	}
	

    /**
     * @name OA 登录
     * @desc OA 登录操作
     * @method post
     */
	public function post()
	{
		$form = array(
			'username' => FC_str('用户名')->min(5)->max(20)->required(),
			'password' => FC_str('密码')->min(6)->max(8)->required(),
			'captcha' => FC_str('图形验证码')->min(6)->max(6)->required()
		);
		list($data, $error) = $this->check($form, $_POST, 'VE');
		if($error)
		{
			$this->load->vars('error', $error);
			return $this->index();
		}
		
		// image verify
		if($this->session->check_verify_image($data['captcha']) == FALSE)
		{
			$this->load->vars('error', array('图形验证码有误'));
			return $this->index();
		}
		
		// login
		$status = $this->session->check_login($data['username'], $data['password']);
		if($status == OA_Session::ERROR_LOGIN_FAILED)
		{
			$this->load->vars('error', array('用户不存在或密码错误'));
			return $this->index();
		}
		if($status == OA_Session::ERROR_LOGIN_FAILED_AND_LOCKED)
		{
			show_error(
				sprintf('IP: <b>%s</b> 验证次数过多，会话已被锁定。请联系管理员或 %d 秒后重试',
				$this->session->userdata('ip_address'), 
				OA_Session::LOGIN_FAILED_FREEZED_TIME));
		}
		
		$this->load->helper('url');
		redirect('/main');
		
	}


    /**
     * @name 找回用户密码输入信息页面
     * @desc 加载用户密码找回，信息输入页面
     */
    public function find_password_load()
    {
        $this->load->view('find_password', array(
			'token_name' => $this->security->get_csrf_token_name(),
			'token_hash' => $this->security->get_csrf_hash(),
        ));
    }


    /**
     * @name 找回用户密码
     * @desc 找回用户密码，发送邮件给用户
     * @method post
     */
    public function find_password()
    {
        list($safe_vars) = $this->check(array(
			'username' => FC_str('用户名')->min(5)->max(20)->required(),
            'email' => FC_email('邮件地址')->max(64)->required(),
        ));

        // Juge whether username and email matched
        $user_info = $this->db
            ->from('user')
            ->where('username', $safe_vars['username'])
            ->where('email', $safe_vars['email'])
            ->where('status', OA_CONST_USER::STATUS_NORMAL)
            ->get()
            ->first_row('array');
        if( ! $user_info)
        {
            show_error('很抱歉，您输入的资料错误，请查证后再输');
        }

        // Check latest active record
        $latest_active_info = $this->db
            ->from('find_user_password')
            ->where('u_id', $user_info['id'])
            ->get()
            ->first_row('array');
        if($latest_active_info)
        {
            if($latest_active_info['expire_dateline'] > time())
            {
                show_error('您的密码找回申请已经提交，请等待激活邮件');
            }

            // Delete expire active task
            $this->db
                ->where('u_id', $user_info['id'])
                ->delete('find_user_password');
        }

        $this->db->trans_start();

        // Create active task
        $signature = uniqid();
        $current_dateline = time();
        $active_url = 'http://' . 
            $this->input->server('SERVER_NAME') . ':' .
            $this->input->server('SERVER_PORT'). '/user/active/load?' .
            http_build_query(array(
                'signature' => $signature
            ));
        $this->db->insert('find_user_password', array(
            'u_id' => $user_info['id'],
            'signature' => $signature,
            'expire_dateline' => $current_dateline + 60 * 60 * 24 * 3
        ));

        // Create email task
        $title = '请重置您的月田密码';
        $message = '请点击链接：<a href="'.$active_url.'">'.$active_url.'</a>激活帐号';
        $this->db->insert('email', array(
            'u_id' => $user_info['id'],
            'title' => $title,
            'message' => $message,
            'dateline' => $current_dateline,
            'status' => OA_CONST_MESSAGE::STATUS_INIT,
        ));
        $email_id = $this->db->insert_id();

        $this->db->insert('email_address', array(
            'email_id' => $email_id,
            'u_id' => $u_id,
            'address' => $safe_vars['email'],
            'status' => OA_CONST_MESSAGE::STATUS_INIT,
        ));
        $this->db->trans_complete();

        $this->load->view('info', array(
            'message' => '重置密码提交成功，邮件随后发送，请注意查收',
            'url' => '/'
        ));
    }


    /**
     * @name 用户找回密码/激活页面
     * @desc 加载用户找回密码/激活页面
     */
    public function active_load()
    {
        list($safe_vars) = $this->check(array(
            'signature' => FC_str('激活码')->max(32)->required(),
        ));

        // Check signature
        $query = $this->db
            ->from('find_user_password')
            ->where('signature', $safe_vars['signature'])
            ->get();
        $active_info = $query->first_row('array');
        if( ! $active_info)
        {
            show_error('非法操作');
        }
        if( $active_info['expire_dateline'] < time())
        {
            show_error('很抱歉，您的链接已经过期了');
        }

		// prevent captcha image no change
		header('Cache-Control:no-cache');
		header('Expires:Thu, 01 Jan 1970 00:00:01 GMT');

        $this->load->view('user_active', array(
            'signature' => $safe_vars['signature'], 
			'token_name' => $this->security->get_csrf_token_name(),
			'token_hash' => $this->security->get_csrf_hash(),
        ));
    }


    /**
     * @name 用户找回密码/激活
     * @desc 用户找回密码/激活
     * @method post
     */
    public function active()
    {
        list($safe_vars) = $this->check(array(
            'signature' => FC_str('激活码')->max(32)->required(),
            'password' => FC_str('密码')->min(6)->max(8)->required(),
			'username' => FC_str('用户名')->min(5)->max(20)->required(),
        ));

        // Check user
        $query = $this->db
            ->select('f.expire_dateline, f.signature, u.id, u.username, u.status')
            ->from('find_user_password AS f')
            ->join('user AS u', 'f.u_id=u.id')
            ->where('u.username', $safe_vars['username'])
            ->get();
        $user = $query->first_row('array');
        if( ! $user)
        {
            show_error('非法操作');
        }

        var_dump($user['status']);
        if($user['status'] != OA_CONST_USER::STATUS_NORMAL)
        {
            show_error('很抱歉，您输入的用户名错误');
        }
        
        if($user['expire_dateline'] < time())
        {
            show_error('很抱歉，您的链接已经过期');
        }

        if($user['signature'] !== $safe_vars['signature'])
        {
            show_error('很抱歉，您的链接错误');
        }

        // Change password
        $this->db->trans_start();

        $this->db->where('id', $user['id'])->update('user', array(
            'password' => md5($safe_vars['password'])
        ));
        $this->db->where('u_id', $user['id'])->delete('find_user_password');
        $this->db->trans_complete();

		$this->load->helper('url');
		redirect('/login');
    }
}

/* End file of login.php */
/* Location: ./application/controller/login.php */
